package com.newgoldcurrency.activities.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;

import com.anythink.banner.api.ATBannerListener;
import com.anythink.banner.api.ATBannerView;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.AdError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.activities.ChatActivity;
import com.newgoldcurrency.adapter.MinerAdapter;
import com.newgoldcurrency.bean.MinerBean;
import com.newgoldcurrency.databinding.FragmentMinerBinding;
import com.newgoldcurrency.utils.NettyClient;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MinerFragment extends Fragment {
    private FragmentMinerBinding binding;
    private MainActivity activity;
    private final List<Call> calls = new ArrayList<>();
    private final List<MinerBean> data = new ArrayList<>();
    private MinerAdapter adp;
    private NettyClient nettyClient;
    private String superId = "";
    private long mClickTime;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    @SuppressLint({"SetTextI18n"})
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (MainActivity) getActivity();
        binding = FragmentMinerBinding.inflate(inflater, container, false);
        adp = new MinerAdapter(activity, data);
        binding.minerList.setAdapter(adp);
        binding.minerSuper.setOnClickListener(v -> {
            if (checkDoubleClick()){
                binding.minerMsgNum.setText("");
                binding.minerMsgNum.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.transparent,null));
                startActivity(new Intent(activity,ChatActivity.class).putExtra("mineId", App.userBean.id).putExtra("id", superId).putExtra("code", binding.minerSuperCode.getText().toString()));
            }
        });
        binding.minerList.setOnItemClickListener((parent, view, position, id) -> {
            if (checkDoubleClick()){
                Intent intent = new Intent(activity, ChatActivity.class).putExtra("id", data.get(position).id).putExtra("mineId", App.userBean.id).putExtra("code", data.get(position).invitation_code);
                startActivity(intent);
            }
        });
        initBanner();
        nettyClient = new NettyClient(jo -> activity.runOnUiThread(() -> {
            switch (jo.get("cmd").getAsString()) {
                case "MESSAGE":
                    if (superId.equals(jo.get("from").getAsString())) {
                        if (jo.get("msg").getAsInt()>99){
                            binding.minerMsgNum.setText("99+");
                        }else {
                            binding.minerMsgNum.setText(jo.get("msg").getAsString());
                        }
                        binding.minerMsgNum.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.msg_num,null));
                    }else {
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).id.equals(jo.get("from").getAsString())) {
                                data.get(i).message_count = jo.get("msg").getAsString();
                                break;
                            }
                        }
                        Collections.sort(data);
                        adp.notifyDataSetChanged();
                    }
                    break;
                case "CONNECT":
                    break;
            }
        }));
        return binding.getRoot();
    }
    private void refresh(){
        data.clear();
        HashMap<String, String> map = new HashMap<>();
        map.put("token", App.sp.getString("token", ""));
        Network.post(map, "miner/getMyMiner", call -> {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @SuppressLint({"SetTextI18n"})
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    activity.runOnUiThread(() -> {
                        try {
                            String str= Objects.requireNonNull(response.body()).string();
                            if (Tools.isJson(str)){
                                JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                if (jo.get("message").getAsString().equals("Get Miner success")) {
                                    JsonObject res = jo.get("data").getAsJsonObject();
                                    if (res.has("super")){
                                        JsonObject super_ = res.get("super").getAsJsonObject();
                                        binding.minerSuperCode.setText(super_.get("invitation_code").getAsString());
                                        superId = super_.get("id").getAsString();
                                        if (super_.get("message_count").getAsInt() == 0) {
                                            binding.minerMsgNum.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.transparent,null));
                                            binding.minerMsgNum.setText("");
                                        } else {
                                            binding.minerMsgNum.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.msg_num,null));
                                            if (super_.get("message_count").getAsInt() > 99) {
                                                binding.minerMsgNum.setText("99+");
                                            }else {
                                                if (super_.get("message_count").getAsInt()<10){
                                                    binding.minerMsgNum.setText(" "+super_.get("message_count").getAsString()+" ");
                                                }else {
                                                    binding.minerMsgNum.setText(super_.get("message_count").getAsString());
                                                }
                                            }
                                        }
                                    }else {
                                        binding.minerMsgNum.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.transparent,null));
                                        binding.minerMsgNum.setText("");
                                        binding.minerSuperCode.setText(getString(R.string.deleted_account));
                                    }
                                    data.addAll(new Gson().fromJson(res.get("miners"), new TypeToken<List<MinerBean>>() {
                                    }.getType()));
                                    Collections.sort(data);
                                    binding.minerMiners.setText(getString(R.string.your_miner, String.valueOf(data.size())));
                                    adp.notifyDataSetChanged();
                                } else {
                                    Tools.toast(jo.get("message").getAsString());
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
            calls.add(call);
        });
    }
    @Override
    public void onStart() {
        super.onStart();
        refresh();
        nettyClient.start("MINER");
    }
    private void initBanner() {
        ATBannerView mBannerView = new ATBannerView(activity);
        mBannerView.setPlacementId("b620dbae9744a9");
        int width = Tools.screenWidthPixels(activity);
        int height =  ViewGroup.LayoutParams.WRAP_CONTENT;
        mBannerView.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        mBannerView.setBannerAdListener(new ATBannerListener() {
            @Override
            public void onBannerLoaded() {
                if (binding!=null)binding.minerBanner.setVisibility(View.VISIBLE);
            }
            @Override
            public void onBannerFailed(AdError adError) {
            }
            @Override
            public void onBannerClicked(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerShow(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerClose(ATAdInfo atAdInfo) {
                if (binding!=null)binding.minerBanner.setVisibility(View.GONE);
            }
            @Override
            public void onBannerAutoRefreshed(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerAutoRefreshFail(AdError adError) {
            }
        });
        binding.minerBanner.addView(mBannerView);
        if (App.ShowBean.hasBanner){
            mBannerView.loadAd();
//            binding.minerBanner.setVisibility(View.VISIBLE);
        }else {
            binding.minerBanner.setVisibility(View.GONE);
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        nettyClient.close();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        for (Call c : calls) c.cancel();
        binding=null;
    }
}